home *** CD-ROM | disk | FTP | other *** search
/ Java Certification Exam Guide / McGrawwHill-JavaCertificationExamGuide.iso / pc / Web Links and Code / code / chap12 / ClickApplet.java < prev    next >
Encoding:
Java Source  |  1997-04-20  |  1.1 KB  |  56 lines

  1. import java.awt.*;
  2. import java.applet.*;
  3.  
  4. public class ClickApplet extends Applet {
  5.  
  6.    boolean clicked;
  7.    int counter;
  8.  
  9.    public void init() {
  10.       add(new ClickCanvas(this));
  11.       add(new ClickCanvas(this));
  12.    }
  13.  
  14.    public boolean mouseDown(Event e, int x, int y) {
  15.       synchronized (this) {
  16.          clicked = true;
  17.          notify();
  18.       }
  19.       counter++;
  20.  
  21.       Thread.currentThread().yield();
  22.       clicked = false;
  23.       return super.mouseDown(e, x, y);
  24.    }
  25.  
  26. }
  27.  
  28. class ClickCanvas extends Canvas implements Runnable {
  29.    ClickApplet applet;
  30.  
  31.    ClickCanvas(ClickApplet applet) {
  32.       this.applet = applet;
  33.       resize(30, 30);
  34.       new Thread(this).start();
  35.    }
  36.  
  37.    public void run() {
  38.       while (true) {
  39.          synchronized (applet) {
  40.             while (!applet.clicked) {
  41.                try {
  42.                   applet.wait();
  43.                } catch (InterruptedException x) {
  44.                }
  45.             }
  46.          }
  47.          repaint();
  48.       }
  49.    }
  50.  
  51.    public void paint(Graphics g) {
  52.       g.drawString(new Integer(applet.counter).toString(), 10, 20);
  53.    }
  54.  
  55. }
  56.